package store.lunangangster.engine.impl.bpmn.behavior;

import java.util.List;
import store.lunangangster.bpmn.model.UserTask;
import store.lunangangster.engine.NodeFlowException;
import store.lunangangster.engine.impl.Context;
import store.lunangangster.engine.impl.entity.ExecutionEntity;
import store.lunangangster.engine.impl.entity.TaskEntity;

public class UserTaskBehavior extends TaskBehavior {

  @Override
  public void doBehavior(ExecutionEntity execution) {
    UserTask userTask = (UserTask) execution.getCurrentFlowElement();
    String username = userTask.getCandidate().getUsername();
    String group = userTask.getCandidate().getGroup();

    TaskEntity taskEntity = Context.getProcessEngineConfiguration()
        .getTaskEntityManager().createTaskByExecutionAndUserTask(execution, userTask);

    // insert and get taskId
    Context.getProcessEngineConfiguration().getTaskEntityManager().insert(taskEntity);
    if (username != null) {
      taskEntity.addCandidateUser(username);
    }
    if (group != null) {
      taskEntity.addCandidateGroup(group);
    }
    // set Time
    execution.setStartTime(Context.getProcessEngineConfiguration().getEngineClock().now());
  }

  @Override
  public void trigger(ExecutionEntity execution) {
    Context.getProcessEngineConfiguration().getHistoryManager()
        .createNewHistory(execution, execution.getCurrentFlowElement(), "TRIGGERED");

    List<TaskEntity> taskEntities = Context.getProcessEngineConfiguration().getTaskEntityManager()
        .selectTaskByExecutionId(execution.getId());

    // finish

    // 判断是否所有TaskEntity已经被删除，注意此时事务还未提交
    for (TaskEntity taskEntity : taskEntities) {
      if (!taskEntity.isDelete()) {
        throw new NodeFlowException("存在任务: " + taskEntity.getName() + "还未完成，无法trigger Execution");
      }
    }

    // go next
    goNext(execution);
  }
}
